package bswd;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class HtmlUnitTest3 {
	public static void main(String[] args) {
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("username:");
			final String username = reader.readLine();
			System.out.print("password: ");
//			StringBuilder sb = new StringBuilder();
//			int c;
//			while((c = reader.read()) != 10){
//				sb.append((char)c);
//				System.out.print("\b*");
//			}
//			System.out.println(sb);
			String password = reader.readLine();
			
			WebClient client = new WebClient(BrowserVersion.INTERNET_EXPLORER_6);
			client.setJavaScriptEnabled(false);
			HtmlPage page = client.getPage("http://jw.nju.edu.cn/165/menu165.html");
			HtmlElement the_table = page.getElementsByTagName("table").get(14);
			//System.out.println(the_table.asXml());
			List<HtmlElement> aList = the_table.getElementsByTagName("a");
			List<HtmlElement> newList = new ArrayList<HtmlElement>();
			for(HtmlElement elem : aList){
				if(elem.getTextContent().contains("教学服务平台")){
					newList.add(elem);
				}
			}
			for(HtmlElement elem : newList){
				HtmlPage tempPage = client.getPage(elem.getAttribute("href"));
				List<HtmlForm> forms = tempPage.getForms();
				HtmlForm login_form = forms.get(0);
				HtmlInput input = login_form.getInputByName("userName");
				input.setValueAttribute(username);
				input = login_form.getInputByName("password");
				input.setValueAttribute(password);
				input = login_form.getInputByValue("");
				System.out.println(((HtmlPage) input.click()).asXml());
				break;
			}
		}catch(Exception e){
			System.err.println(e.getMessage());
		}
	}
}
